package com.slz3.business.module.messageManagement.mesUser.steward;

import com.slz3.business.frame.steward.FindJoinSteward;
import com.slz3.business.frame.util.VE;
import com.slz3.business.module.messageManagement.mesUser.domain.MesUser;
import com.slz3.business.module.messageManagement.mesUser.domain.MesUserCondition;
import com.slz3.business.module.messageManagement.mesUser.domain.MesUserFactory;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.util.MultiValueMap;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

public class MesUserSpecification {

    public static FindJoin findJoin(MultiValueMap<String, String> params) {
        return new FindJoin(params);
    }

    private static class FindJoin implements Specification<MesUser> {

        private MultiValueMap<String, String> params;
        private MesUserCondition condition;

        public FindJoin(MultiValueMap<String, String> params) {
            this.params = params;

            this.condition = MesUserFactory.newMesUserCondition(params);

        }

        @Override
        public Predicate toPredicate(Root<MesUser> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

            final List<Predicate> predicateList = new ArrayList<>();

            predicateList.addAll(FindJoinSteward.appoint(root, cb, MesUser.class, params));

//            predicateList.add(cb.equal(root.get("validFlag").as(ValidFlag.class), ValidFlag.VALID));
            if (VE.isNotEmpty(condition.getSerSendTimeStart())) {
                predicateList.add(cb.greaterThanOrEqualTo(root.get("serSendTime"), condition.getSerSendTimeStart()));
            }
            if (VE.isNotEmpty(condition.getSerSendTimeEnd())){
                predicateList.add(cb.lessThanOrEqualTo(root.get("serSendTime"), condition.getSerSendTimeEnd()));
            }

            return predicateList.size() > 0 ? cb.and(predicateList.toArray(new Predicate[]{})) : null;

        }

    }

}
